package github.sf.fw.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import java.io.IOException;
import java.net.URL;

/**
 * @author zhoup
 * @since 2023/5/10
 */
public class ConfigUtil {
    private ConfigUtil() {
    }

    public static URL findResource(String fileName) {
        return Thread.currentThread().getContextClassLoader().getResource(fileName);
    }

    public static <T> T getConfInstanceByYaml(Class<T> clazz, String fileName) {
        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
        try {
            URL resource = findResource(fileName);
            return objectMapper.readValue(resource, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static long getWorkId() {
        return Long.parseLong(getOrDefault("wflow.work.id", "1"));
    }

    public static long getDataCenterId() {
        return Long.parseLong(getOrDefault("wflow.datacneter.id", "1"));
    }

    public static String getOrDefault(String key, String defaultValue) {
        String env = System.getenv(key);
        if (StrUtil.isEmpty(env)) {
            return getPropOrDefault(key, defaultValue);
        }
        return env;
    }

    public static String getPropOrDefault(String key, String defaultValue) {
        return System.getProperty(key, defaultValue);
    }

    public static String getEnvOrDefault(String name, String defaultValue) {
        String getenv = System.getenv(name);
        return StrUtil.isEmpty(getenv) ? defaultValue : getenv;
    }
}
